'use client';

import type { TMetadata } from '@/types';
import { NavbarPage } from '@/app/[locale]/navbar';
import FooterPage from '@/app/[locale]/footer';
import useToast from '@/hooks/useToast';
import ErrorPage from '@/app/[locale]/error/error';
import LoadPage from '@/app/[locale]/load/load';
import Nodata from '@/app/[locale]/common/nodata/nodata';
import useUser from '@/hooks/useUser';
import { useQuery } from '@tanstack/react-query';
import { search } from '@/services/api';
import type { IPagination, IPost, IQueryParams } from '@/interfaces';
import { type ChangeEvent, useEffect, useState } from 'react';
import Link from 'next/link';
import Alert from '@/app/[locale]/alert/alert';
import classNames from 'classnames';
import AlertLoad from '@/app/[locale]/alert/load';
import { useSearchParams } from 'next/navigation';
import { useTranslations } from 'use-intl';

export default function SearchPage({ metadata }: { metadata: TMetadata }) {
  return (
    <>
      <NavbarPage metadata={metadata} />
      <Search metadata={metadata} />
      <FooterPage metadata={metadata} />
    </>
  );
}

const Search = ({ metadata }: { metadata: TMetadata }) => {
  const t = useTranslations('SearchPage');
  const userQuery = useUser(metadata);
  const { show } = useToast();
  const [name, setName] = useState('');
  const [params, setParams] = useState<IQueryParams>({
    page: 0,
    size: 10,
  });
  const searchParams = useSearchParams();

  useEffect(() => {
    const value = searchParams.get('v');
    if (value?.trim()) {
      setName((prevState) => value.trim());
    }
  }, [searchParams]);

  const searchQuery = useQuery(
    ['/search', name, params],
    async (context) => {
      return (await search({
        query: {
          ...(context.queryKey[2] as any),
          name: encodeURIComponent(context.queryKey[1] + ''),
        },
      })) as IPagination<IPost>;
    },
    {
      enabled: !!(name && name.length > 1),
      keepPreviousData: true,
    },
  );

  function onClickPrevious() {
    const data = searchQuery.data;
    if (!data) {
      show({
        type: 'DANGER',
        message: t('dataNotExists'),
      });
      return;
    }

    const page = Math.max(0, data.pageable.page - 1);
    setParams({ ...params, page });
  }

  function onClickNext() {
    const data = searchQuery.data;
    if (!data) {
      show({
        type: 'DANGER',
        message: t('dataNotExists'),
      });
      return;
    }

    const page = Math.min(data.pageable.pages, data.pageable.page + 1);
    setParams({ ...params, page });
  }

  function onChangeName(e: ChangeEvent<HTMLInputElement>) {
    setName(e.target.value);
  }

  if (userQuery.data) {
    return (
      <div className="col px-0">
        <div className="card border-0">
          <div className="card-body">
            <div className="container vstack gap-4 py-4">
              <input
                name="name"
                value={name}
                onChange={onChangeName}
                className="form-control"
                type="search"
                placeholder={t('pleaseEnterSearchContent')}
                aria-label="name"
              />

              {searchQuery.data && (
                <div className="vstack gap-4">
                  {searchQuery.data.content.length > 0 && (
                    <div className="card">
                      <div className="card-header user-select-none">
                        {t('relatedData')}
                      </div>
                      <div className="list-group list-group-flush">
                        {searchQuery.data.content.map((item) => {
                          return (
                            <Link
                              key={item.id}
                              href={`/posts/${item.id}`}
                              className="list-group-item list-group-item-action"
                              target="_blank"
                            >
                              {item.name}
                            </Link>
                          );
                        })}
                      </div>
                    </div>
                  )}

                  {searchQuery.data.content.length === 0 && <Nodata />}

                  {searchQuery.data.pageable.pages > 1 && (
                    <nav>
                      <ul className="pagination pagination-sm justify-content-center my-4 user-select-none">
                        <li
                          className={classNames('page-item', {
                            disabled: !searchQuery.data.pageable.previous,
                          })}
                        >
                          <a
                            onClick={onClickPrevious}
                            className="page-link cursor-pointer"
                          >
                            {t('previousPage')}
                          </a>
                        </li>
                        <li
                          className={classNames('page-item', {
                            disabled: !searchQuery.data.pageable.next,
                          })}
                        >
                          <a
                            onClick={onClickNext}
                            className="page-link cursor-pointer"
                          >
                            {t('nextPage')}
                          </a>
                        </li>
                      </ul>
                    </nav>
                  )}
                </div>
              )}

              {searchQuery.isError && (
                <Alert message={searchQuery.error} type="error" />
              )}

              {name && name.length > 1 && searchQuery.isLoading && (
                <AlertLoad />
              )}

              <div></div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (userQuery.error) {
    return <ErrorPage error={userQuery.error} />;
  }

  return <LoadPage />;
};
